import { Suspense, useRef, useState, useEffect } from 'react'
import { Canvas, useFrame } from '@react-three/fiber'
import { OrbitControls, Environment, Stage, PerspectiveCamera, useGLTF } from '@react-three/drei'
import * as THREE from 'three'
import { useStore } from '../store/useStore'
import { toast } from 'react-toastify'
import Tooltip from './Tooltip'
import { useIsMobile, useIsTouchDevice } from '../hooks/useMediaQuery'

// 3D模型组件
function Model({ url, autoRotate, materialType = 'standard', onModelLoad, modelScale = 1, rotationSpeed = 0.3 }) {
  const modelRef = useRef()
  
  // 检查是否是内置演示模型
  const isBuiltinDemo = url === '__builtin_demo__'
  
  // 将MeshyAI的CDN URL转换为代理URL
  const getProxyUrl = (originalUrl) => {
    if (!originalUrl || isBuiltinDemo) return originalUrl
    // 确保originalUrl是字符串
    if (typeof originalUrl !== 'string') {
      console.warn('⚠️ getProxyUrl收到非字符串URL:', originalUrl)
      return null
    }
    if (originalUrl.includes('assets.meshy.ai')) {
      // 将 https://assets.meshy.ai/... 转换为 /meshy-assets/...
      return originalUrl.replace('https://assets.meshy.ai', '/meshy-assets')
    }
    return originalUrl
  }
  
  const proxyUrl = getProxyUrl(url)
  
  // 只在非内置模型时加载外部文件
  const gltf = !isBuiltinDemo ? useGLTF(proxyUrl) : null
  
  // 计算模型统计信息
  useEffect(() => {
    if (!gltf?.scene || isBuiltinDemo) return
    
    let vertices = 0
    let faces = 0
    
    gltf.scene.traverse((child) => {
      if (child.isMesh) {
        const geometry = child.geometry
        if (geometry.index) {
          vertices += geometry.attributes.position.count
          faces += geometry.index.count / 3
        }
      }
    })
    
    // 计算模型包围盒
    const box = new THREE.Box3().setFromObject(gltf.scene)
    const size = box.getSize(new THREE.Vector3())
    
    onModelLoad?.({
      vertices: Math.floor(vertices),
      faces: Math.floor(faces),
      size: {
        x: size.x.toFixed(2),
        y: size.y.toFixed(2),
        z: size.z.toFixed(2)
      }
    })
  }, [gltf, isBuiltinDemo, onModelLoad])
  
  // 自动旋转动画
  useFrame((state, delta) => {
    if (autoRotate && modelRef.current) {
      modelRef.current.rotation.y += delta * rotationSpeed
    }
  })

  // 如果是内置演示模型，创建一个简单的几何体
  if (isBuiltinDemo) {
    return (
      <group ref={modelRef}>
        {/* 创建一个组合的演示模型 */}
        <mesh position={[0, 0, 0]}>
          <boxGeometry args={[1.5, 1.5, 1.5]} />
          <meshStandardMaterial 
            color="#3b82f6" 
            metalness={0.6} 
            roughness={0.4}
            wireframe={materialType === 'wireframe'}
          />
        </mesh>
        <mesh position={[0, 1.2, 0]}>
          <sphereGeometry args={[0.5, 32, 32]} />
          <meshStandardMaterial 
            color="#60a5fa" 
            metalness={0.5} 
            roughness={0.3}
            wireframe={materialType === 'wireframe'}
          />
        </mesh>
        <mesh position={[0, -1.2, 0]}>
          <cylinderGeometry args={[0.6, 0.6, 0.4, 32]} />
          <meshStandardMaterial 
            color="#2563eb" 
            metalness={0.7} 
            roughness={0.2}
            wireframe={materialType === 'wireframe'}
          />
        </mesh>
      </group>
    )
  }

  // 外部模型
  const clonedScene = gltf.scene.clone()

  // 应用材质
  if (modelRef.current) {
    clonedScene.traverse((child) => {
      if (child.isMesh) {
        switch (materialType) {
          case 'wireframe':
            child.material.wireframe = true
            break
          case 'normal':
            child.material = new THREE.MeshNormalMaterial()
            break
          default:
            child.material.wireframe = false
        }
      }
    })
  }

  return (
    <primitive 
      ref={modelRef}
      object={clonedScene} 
      scale={modelScale}
      position={[0, 0, 0]}
    />
  )
}

// 加载占位符
function LoadingPlaceholder() {
  return (
    <mesh>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color="#e2e8f0" />
    </mesh>
  )
}

// 预设视角
const CAMERA_PRESETS = {
  front: { position: [0, 0, 10], name: '正面' },
  back: { position: [0, 0, -10], name: '背面' },
  left: { position: [-10, 0, 0], name: '左侧' },
  right: { position: [10, 0, 0], name: '右侧' },
  top: { position: [0, 10, 0], name: '俯视' },
  bottom: { position: [0, -10, 0], name: '仰视' },
  diagonal: { position: [7, 7, 7], name: '对角' }
}

export default function ModelViewerEnhanced() {
  const { modelUrl, currentStep, isGenerating, modelData, setModelData } = useStore()
  const [autoRotate, setAutoRotate] = useState(true)
  const [showGrid, setShowGrid] = useState(false)
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [lightIntensity, setLightIntensity] = useState(1.2)
  const [modelInfo, setModelInfo] = useState(null)
  const [loadingProgress, setLoadingProgress] = useState(0)
  const [showModelInfo, setShowModelInfo] = useState(true)
  const [showDownloadMenu, setShowDownloadMenu] = useState(false)
  
  // 调试：输出当前 modelUrl
  useEffect(() => {
    console.log('🔍 ModelViewer 状态:')
    console.log('  - modelUrl:', modelUrl)
    console.log('  - currentStep:', currentStep)
    console.log('  - isGenerating:', isGenerating)
  }, [modelUrl, currentStep, isGenerating])
  
  // 当模型URL变化时，清除旧的模型信息并重新显示信息面板
  useEffect(() => {
    setModelInfo(null)
    setShowModelInfo(true)
  }, [modelUrl])
  const [ambientIntensity, setAmbientIntensity] = useState(0.6)
  const [materialType, setMaterialType] = useState('standard')
  const [showControls, setShowControls] = useState(false)
  const [modelScale, setModelScale] = useState(1)
  const [rotationSpeed, setRotationSpeed] = useState(0.3)
  const [backgroundColor, setBackgroundColor] = useState('#1a1a2e')
  
  const controlsRef = useRef()
  const canvasRef = useRef()
  const containerRef = useRef()

  // 移动端检测
  const isMobile = useIsMobile()
  const isTouchDevice = useIsTouchDevice()

  // 重置相机视角
  const resetCamera = () => {
    if (controlsRef.current) {
      controlsRef.current.reset()
      toast.success('视角已重置')
    }
  }

  // 应用预设视角
  const applyPreset = (preset) => {
    if (controlsRef.current) {
      const camera = controlsRef.current.object
      camera.position.set(...preset.position)
      controlsRef.current.update()
      toast.success(`切换到${preset.name}视角`)
    }
  }

  // 截图功能
  const takeScreenshot = () => {
    if (canvasRef.current) {
      try {
        const canvas = canvasRef.current.querySelector('canvas')
        if (canvas) {
          canvas.toBlob((blob) => {
            const url = URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = `3d-model-${Date.now()}.png`
            link.click()
            URL.revokeObjectURL(url)
            toast.success('📸 截图已保存！')
          })
        }
      } catch (error) {
        console.error('截图失败:', error)
        toast.error('截图失败，请重试')
      }
    }
  }

  // 全屏切换
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      containerRef.current?.requestFullscreen()
      setIsFullscreen(true)
      toast.success('已进入全屏模式（按 ESC 退出）')
    } else {
      document.exitFullscreen()
      setIsFullscreen(false)
    }
  }


  // 下载模型文件
  const downloadModel = async (format) => {
    if (!modelData?.modelUrls) {
      toast.error('模型数据不可用')
      return
    }

    const formatUrls = {
      glb: modelData.modelUrls.glb,
      fbx: modelData.modelUrls.fbx,
      obj: modelData.modelUrls.obj,
      usdz: modelData.modelUrls.usdz,
      stl: modelData.modelUrls.stl,
      gltf: modelData.modelUrls.gltf,
      dae: modelData.modelUrls.dae,
      ply: modelData.modelUrls.ply,
      '3ds': modelData.modelUrls['3ds'],
      blend: modelData.modelUrls.blend
    }

    const url = formatUrls[format]
    if (!url) {
      toast.error(`${format.toUpperCase()} 格式不可用`)
      return
    }

    try {
      toast.info(`正在下载 ${format.toUpperCase()} 格式...`, { autoClose: 1500 })
      
      // 使用代理URL
      const proxyUrl = url.includes('assets.meshy.ai') 
        ? url.replace('https://assets.meshy.ai', '/meshy-assets')
        : url

      const response = await fetch(proxyUrl)
      const blob = await response.blob()
      const downloadUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = `3d-model-${Date.now()}.${format}`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(downloadUrl)
      
      toast.success(`✅ ${format.toUpperCase()} 已下载！`, { autoClose: 2000 })
      // 不关闭菜单，允许连续下载多个格式
    } catch (error) {
      console.error('下载失败:', error)
      toast.error(`下载 ${format.toUpperCase()} 失败，请重试`)
    }
  }

  // 一键下载所有格式
  const downloadAllFormats = async () => {
    if (!modelData?.modelUrls) {
      toast.error('模型数据不可用')
      return
    }

    const availableFormats = []
    const formatList = ['glb', 'fbx', 'obj', 'usdz', 'stl', 'gltf', 'dae', 'ply', '3ds', 'blend']
    
    formatList.forEach(format => {
      if (modelData.modelUrls[format]) {
        availableFormats.push(format)
      }
    })

    if (availableFormats.length === 0) {
      toast.error('没有可下载的格式')
      return
    }

    toast.info(`🚀 开始批量下载 ${availableFormats.length} 个格式...`, { autoClose: 2000 })

    let successCount = 0
    let failCount = 0

    for (const format of availableFormats) {
      try {
        const url = modelData.modelUrls[format]
        const proxyUrl = url.includes('assets.meshy.ai') 
          ? url.replace('https://assets.meshy.ai', '/meshy-assets')
          : url

        const response = await fetch(proxyUrl)
        const blob = await response.blob()
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `3d-model-${Date.now()}.${format}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        
        successCount++
        await new Promise(resolve => setTimeout(resolve, 500)) // 延迟避免浏览器阻止
      } catch (error) {
        console.error(`下载 ${format} 失败:`, error)
        failCount++
      }
    }

    if (successCount > 0) {
      toast.success(`✅ 已成功下载 ${successCount} 个文件！${failCount > 0 ? ` (${failCount}个失败)` : ''}`)
    } else {
      toast.error('❌ 所有文件下载失败')
    }
    
    setShowDownloadMenu(false)
  }

  // 下载缩略图
  const downloadThumbnail = async () => {
    if (!modelData?.thumbnailUrl) {
      toast.error('缩略图不可用')
      return
    }

    try {
      toast.info('正在下载缩略图...', { autoClose: 1500 })
      
      const proxyUrl = modelData.thumbnailUrl.includes('assets.meshy.ai')
        ? modelData.thumbnailUrl.replace('https://assets.meshy.ai', '/meshy-assets')
        : modelData.thumbnailUrl

      const response = await fetch(proxyUrl)
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `3d-model-thumbnail-${Date.now()}.png`
      link.click()
      window.URL.revokeObjectURL(url)
      
      toast.success('✅ 缩略图已下载！', { autoClose: 2000 })
      // 不关闭菜单，允许继续下载其他格式
    } catch (error) {
      console.error('下载缩略图失败:', error)
      toast.error('下载缩略图失败，请重试')
    }
  }

  // 监听全屏变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement)
    }
    document.addEventListener('fullscreenchange', handleFullscreenChange)
    return () => document.removeEventListener('fullscreenchange', handleFullscreenChange)
  }, [])

  // 点击外部关闭下载菜单
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (showDownloadMenu && !e.target.closest('.download-menu-container')) {
        setShowDownloadMenu(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [showDownloadMenu])

  return (
    <div 
      ref={containerRef}
      className={`glass-effect-dark rounded-2xl p-6 border border-white/10 card-hover w-full ${
        isFullscreen ? 'fixed inset-0 z-50 rounded-none' : ''
      }`}
    >
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-bold text-white flex items-center space-x-2">
          <span className="text-3xl">🎨</span>
          <span>3D 模型预览</span>
          {modelUrl && (
            <span className="text-sm font-normal text-green-400 flex items-center space-x-1">
              <span className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></span>
              <span>已加载</span>
            </span>
          )}
        </h2>
        
        {modelUrl && (
          <div className="flex items-center space-x-2">
            {/* 控制面板切换 */}
            <Tooltip content="显示/隐藏控制面板">
              <button
                onClick={() => setShowControls(!showControls)}
                className={`group px-3 py-2 text-xs md:text-sm rounded-lg transition-all duration-300 border flex items-center space-x-1 hover:scale-105 shadow-sm ${
                  showControls 
                    ? 'bg-accent-purple/20 text-accent-purple border-accent-purple/50' 
                    : 'bg-white/5 hover:bg-white/10 text-gray-300 hover:text-white border-white/10 hover:border-accent-purple/50'
                }`}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
                </svg>
                <span className="hidden md:inline">控制</span>
              </button>
            </Tooltip>

            {/* 截图按钮 */}
            <Tooltip content="截图（保存当前视角）">
              <button
                onClick={takeScreenshot}
                className="group px-3 py-2 text-xs md:text-sm bg-white/5 hover:bg-white/10 text-gray-300 hover:text-white rounded-lg transition-all duration-300 border border-white/10 hover:border-accent-blue/50 flex items-center space-x-1 hover:scale-105 shadow-sm hover:shadow-md hover:shadow-accent-blue/30"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                <span className="hidden md:inline">截图</span>
              </button>
            </Tooltip>

            {/* 全屏按钮 */}
            <Tooltip content={isFullscreen ? "退出全屏 (ESC)" : "全屏查看 (F)"}>
              <button
                onClick={toggleFullscreen}
                className="group px-3 py-2 text-xs md:text-sm bg-white/5 hover:bg-white/10 text-gray-300 hover:text-white rounded-lg transition-all duration-300 border border-white/10 hover:border-accent-cyan/50 flex items-center space-x-1 hover:scale-105 shadow-sm hover:shadow-md hover:shadow-accent-cyan/30"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  {isFullscreen ? (
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  ) : (
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
                  )}
                </svg>
                <span className="hidden md:inline">{isFullscreen ? '退出' : '全屏'}</span>
              </button>
            </Tooltip>


            {/* 下载按钮 */}
            {modelData?.modelUrls && (
              <div className="relative download-menu-container">
                <Tooltip content="下载3D模型（多种格式）">
                  <button
                    onClick={() => setShowDownloadMenu(!showDownloadMenu)}
                    className="group px-3 py-2 text-xs md:text-sm bg-gradient-to-r from-accent-purple to-accent-blue hover:from-accent-purple/80 hover:to-accent-blue/80 text-white rounded-lg transition-all duration-300 border border-accent-purple/50 flex items-center space-x-1 hover:scale-105 shadow-sm hover:shadow-md hover:shadow-accent-purple/50"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                    </svg>
                    <span className="hidden md:inline">下载</span>
                  </button>
                </Tooltip>

                {/* 下载菜单 */}
                {showDownloadMenu && (
                  <div className="absolute right-0 mt-2 w-48 bg-dark-200 border border-white/10 rounded-lg shadow-xl z-50 animate-scale-in overflow-hidden">
                    <div className="p-2 space-y-1">
                      <div className="px-3 py-2 text-xs text-gray-400 font-semibold border-b border-white/10">
                        选择格式
                      </div>
                      
                      {/* 一键下载全部 */}
                      <button
                        onClick={downloadAllFormats}
                        className="w-full flex items-center justify-between px-3 py-2 text-sm text-white bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 rounded-lg transition-all shadow-sm hover:shadow-md"
                      >
                        <span className="flex items-center space-x-2">
                          <span>⬇️</span>
                          <span className="font-semibold">下载全部</span>
                        </span>
                        <span className="text-xs">批量</span>
                      </button>

                      <div className="border-t border-white/10 my-1"></div>
                      
                      {/* 格式列表 - 统一渲染 */}
                      {[
                        { format: 'glb', icon: '📦', label: 'GLB', desc: '通用' },
                        { format: 'fbx', icon: '🎬', label: 'FBX', desc: '动画' },
                        { format: 'obj', icon: '🔷', label: 'OBJ', desc: '编辑' },
                        { format: 'usdz', icon: '🍎', label: 'USDZ', desc: 'iOS AR' },
                        { format: 'stl', icon: '🖨️', label: 'STL', desc: '3D打印' },
                        { format: 'gltf', icon: '🌐', label: 'GLTF', desc: 'Web标准' },
                        { format: 'dae', icon: '🔄', label: 'DAE', desc: '跨平台' },
                        { format: 'ply', icon: '☁️', label: 'PLY', desc: '点云' },
                        { format: '3ds', icon: '📐', label: '3DS', desc: '3ds Max' },
                        { format: 'blend', icon: '🎨', label: 'Blend', desc: 'Blender' }
                      ].map(({ format, icon, label, desc }) => {
                        const isAvailable = modelData.modelUrls[format]
                        return (
                          <button
                            key={format}
                            onClick={() => isAvailable && downloadModel(format)}
                            disabled={!isAvailable}
                            className={`w-full flex items-center justify-between px-3 py-2 text-sm rounded-lg transition-all ${
                              isAvailable
                                ? 'text-gray-300 hover:text-white hover:bg-white/10 cursor-pointer'
                                : 'text-gray-600 bg-white/5 cursor-not-allowed opacity-50'
                            }`}
                            title={!isAvailable ? '此格式暂不可用' : `下载 ${label} 格式`}
                          >
                            <span className="flex items-center space-x-2">
                              <span className={isAvailable ? '' : 'opacity-50'}>{icon}</span>
                              <span>{label}</span>
                            </span>
                            <span className={`text-xs ${isAvailable ? 'text-gray-500' : 'text-gray-600'}`}>
                              {isAvailable ? desc : '不可用'}
                            </span>
                          </button>
                        )
                      })}

                      {/* 缩略图 */}
                      {modelData.thumbnailUrl && (
                        <>
                          <div className="border-t border-white/10 my-1"></div>
                          <button
                            onClick={downloadThumbnail}
                            className="w-full flex items-center justify-between px-3 py-2 text-sm text-gray-300 hover:text-white hover:bg-white/10 rounded-lg transition-all"
                          >
                            <span className="flex items-center space-x-2">
                              <span>🖼️</span>
                              <span>缩略图</span>
                            </span>
                            <span className="text-xs text-gray-500">PNG</span>
                          </button>
                        </>
                      )}

                      {/* Blender插件 */}
                      <div className="border-t border-white/10 my-1"></div>
                      <div className="px-3 py-2 text-xs text-gray-400 font-semibold">
                        专业精修工具
                      </div>
                      
                      {/* Blender插件下载 */}
                      <button
                        onClick={() => {
                          // 显示多个下载链接
                          const downloadInfo = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Blender插件下载</title>
  <style>
    body { 
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
    }
    .container {
      background: white;
      padding: 40px;
      border-radius: 20px;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
      max-width: 600px;
      width: 100%;
    }
    h1 { 
      color: #2c3e50; 
      margin-bottom: 10px;
      font-size: 28px;
    }
    .subtitle {
      color: #7f8c8d;
      margin-bottom: 30px;
      font-size: 14px;
    }
    .download-option {
      background: #f8f9fa;
      padding: 20px;
      border-radius: 12px;
      margin-bottom: 15px;
      border: 2px solid #e9ecef;
      transition: all 0.3s;
    }
    .download-option:hover {
      border-color: #667eea;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
    }
    .download-option h3 {
      color: #495057;
      margin: 0 0 10px 0;
      font-size: 18px;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    .download-option p {
      color: #6c757d;
      margin: 8px 0;
      font-size: 14px;
      line-height: 1.5;
    }
    .btn {
      display: inline-block;
      padding: 12px 24px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      text-decoration: none;
      border-radius: 8px;
      font-weight: 600;
      transition: all 0.3s;
      margin-top: 10px;
      text-align: center;
    }
    .btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
    .badge {
      display: inline-block;
      padding: 4px 12px;
      background: #28a745;
      color: white;
      border-radius: 12px;
      font-size: 12px;
      font-weight: 600;
    }
    .badge-alt {
      background: #ffc107;
      color: #000;
    }
    .note {
      background: #e7f3ff;
      padding: 15px;
      border-radius: 8px;
      border-left: 4px solid #0066cc;
      margin-top: 20px;
      font-size: 14px;
      color: #004085;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>🔧 Blender插件下载</h1>
    <p class="subtitle">选择下面任意一个下载源</p>

    <div class="download-option">
      <h3>
        🌐 GitHub官方
        <span class="badge">推荐</span>
      </h3>
      <p>最新版本，直接从官方仓库下载</p>
      <p><strong>下载地址：</strong></p>
      <a href="https://github.com/Meshy-ai/meshy-blender-plugin/releases/latest" target="_blank" class="btn">
        访问 GitHub Releases
      </a>
    </div>

    <div class="download-option">
      <h3>
        🚀 GitHub加速镜像
        <span class="badge badge-alt">国内推荐</span>
      </h3>
      <p>如果GitHub访问慢，可以使用加速镜像</p>
      <p><strong>镜像地址1：</strong></p>
      <a href="https://ghproxy.com/https://github.com/Meshy-ai/meshy-blender-plugin/releases" target="_blank" class="btn">
        GHProxy 镜像
      </a>
      <p style="margin-top: 12px;"><strong>镜像地址2：</strong></p>
      <a href="https://mirror.ghproxy.com/https://github.com/Meshy-ai/meshy-blender-plugin/releases" target="_blank" class="btn">
        Mirror 镜像
      </a>
    </div>

    <div class="download-option">
      <h3>📦 直接下载（v0.5.5）</h3>
      <p>直接下载最新稳定版本的ZIP文件</p>
      <a href="https://ghproxy.com/https://github.com/Meshy-ai/meshy-blender-plugin/releases/download/v0.5.5/meshy-blender-plugin-v0.5.5.zip" target="_blank" class="btn">
        下载 v0.5.5.zip
      </a>
    </div>

    <div class="note">
      <strong>💡 下载提示：</strong><br>
      1. 下载得到ZIP文件，<strong>不要解压</strong><br>
      2. 在Blender中安装：Edit → Preferences → Add-ons → Install<br>
      3. 选择下载的ZIP文件即可<br>
      4. 需要Blender版本 ≥ 3.0
    </div>

    <div class="note" style="margin-top: 15px; background: #fff3cd; border-left-color: #ffc107; color: #856404;">
      <strong>⚠️ 如果所有链接都打不开：</strong><br>
      请联系管理员获取插件文件，或稍后重试
    </div>
  </div>
</body>
</html>
                          `
                          const newWindow = window.open('', '_blank')
                          newWindow.document.write(downloadInfo)
                          newWindow.document.close()
                          toast.info('🔧 已打开下载页面')
                        }}
                        className="w-full flex items-center justify-between px-3 py-2 text-sm text-gray-300 hover:text-white hover:bg-gradient-to-r hover:from-orange-500/20 hover:to-amber-500/20 rounded-lg transition-all group cursor-pointer"
                      >
                        <span className="flex items-center space-x-2">
                          <span className="group-hover:scale-110 transition-transform">🔧</span>
                          <span>Blender插件</span>
                        </span>
                        <span className="text-xs text-orange-400">下载</span>
                      </button>

                      {/* 使用指南 */}
                      <button
                        onClick={() => {
                          // 在新窗口显示指南内容
                          const guideContent = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Meshy Blender插件使用指南</title>
  <style>
    body { 
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      line-height: 1.6; 
      max-width: 900px; 
      margin: 40px auto; 
      padding: 20px;
      background: #f5f5f5;
    }
    .container {
      background: white;
      padding: 40px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }
    h2 { color: #34495e; margin-top: 30px; border-left: 4px solid #3498db; padding-left: 15px; }
    h3 { color: #7f8c8d; }
    code { 
      background: #f8f9fa; 
      padding: 2px 6px; 
      border-radius: 3px;
      font-family: monospace;
      color: #e74c3c;
    }
    pre {
      background: #2c3e50;
      color: #ecf0f1;
      padding: 15px;
      border-radius: 5px;
      overflow-x: auto;
    }
    .step {
      background: #e8f4f8;
      padding: 15px;
      margin: 15px 0;
      border-radius: 5px;
      border-left: 4px solid #3498db;
    }
    .warning {
      background: #fff3cd;
      padding: 15px;
      margin: 15px 0;
      border-radius: 5px;
      border-left: 4px solid #ffc107;
    }
    .success {
      background: #d4edda;
      padding: 15px;
      margin: 15px 0;
      border-radius: 5px;
      border-left: 4px solid #28a745;
    }
    a { color: #3498db; text-decoration: none; }
    a:hover { text-decoration: underline; }
    ul { padding-left: 25px; }
    li { margin: 8px 0; }
  </style>
</head>
<body>
  <div class="container">
    <h1>🎨 Meshy Blender插件使用指南</h1>
    
    <div class="success">
      <strong>✨ 推荐使用！</strong> Meshy官方Blender插件可以无缝集成AI生成的3D模型到Blender工作流中。
    </div>

    <h2>📥 下载和安装</h2>
    
    <div class="step">
      <h3>步骤1: 下载插件</h3>
      <p>访问GitHub仓库下载最新版本：</p>
      <p>🔗 <a href="https://github.com/Meshy-ai/meshy-blender-plugin/releases" target="_blank">https://github.com/Meshy-ai/meshy-blender-plugin/releases</a></p>
      <p>下载 <code>meshy-blender-plugin-vX.X.X.zip</code> 文件（不要解压）</p>
    </div>

    <div class="step">
      <h3>步骤2: 安装插件</h3>
      <ol>
        <li>打开 Blender（版本 ≥ 3.0）</li>
        <li>进入 <code>Edit → Preferences → Add-ons</code></li>
        <li>点击右上角的 <code>Install...</code> 按钮</li>
        <li>选择下载的 ZIP 文件</li>
        <li>在插件列表中找到 "Meshy" 并勾选启用</li>
      </ol>
    </div>

    <div class="step">
      <h3>步骤3: 配置API Key</h3>
      <ol>
        <li>在插件设置中找到 "API Key" 输入框</li>
        <li>输入你的 Meshy.ai API Key（与本平台使用同一个）</li>
        <li>点击 "Verify" 验证连接</li>
        <li>看到绿色的 "✓ Connected" 表示成功</li>
      </ol>
    </div>

    <h2>🚀 使用方法</h2>

    <div class="step">
      <h3>方法1: 从插件导入（推荐）</h3>
      <ol>
        <li>在Blender侧边栏（按N键显示）找到 "Meshy" 面板</li>
        <li>点击 "Import Model" 或 "Browse Library"</li>
        <li>从历史记录中选择你生成的模型</li>
        <li>或输入模型的Task ID</li>
        <li>点击 "Import" 自动下载并导入</li>
      </ol>
    </div>

    <div class="step">
      <h3>方法2: 手动导入</h3>
      <ol>
        <li>从本平台下载 GLB 或 FBX 格式</li>
        <li>在Blender中: <code>File → Import → glTF 2.0</code> 或 <code>FBX</code></li>
        <li>选择下载的文件并导入</li>
      </ol>
    </div>

    <h2>💡 使用技巧</h2>

    <div class="success">
      <h3>材质显示</h3>
      <p>导入后切换到 <strong>Material Preview</strong> 或 <strong>Rendered</strong> 模式查看材质效果</p>
      <p>快捷键: <code>Z → 2</code> (Material Preview) 或 <code>Z → 4</code> (Rendered)</p>
    </div>

    <div class="success">
      <h3>常用快捷键</h3>
      <ul>
        <li><code>Tab</code> - 切换编辑模式</li>
        <li><code>G</code> - 移动</li>
        <li><code>S</code> - 缩放</li>
        <li><code>R</code> - 旋转</li>
        <li><code>A</code> - 全选</li>
        <li><code>X</code> - 删除</li>
      </ul>
    </div>

    <h2>❓ 常见问题</h2>

    <div class="warning">
      <h3>Q: 插件安装失败</h3>
      <p><strong>A:</strong> 确保：</p>
      <ul>
        <li>Blender 版本 ≥ 3.0</li>
        <li>下载的是 ZIP 文件（不要解压）</li>
        <li>关闭杀毒软件重试</li>
      </ul>
    </div>

    <div class="warning">
      <h3>Q: 材质不显示</h3>
      <p><strong>A:</strong> 切换视图模式：</p>
      <ul>
        <li>点击右上角的渲染模式图标</li>
        <li>选择 "Material Preview" 或 "Rendered"</li>
        <li>确保在 Shading 工作区查看材质节点</li>
      </ul>
    </div>

    <div class="warning">
      <h3>Q: 模型太大或太小</h3>
      <p><strong>A:</strong> 调整缩放：</p>
      <ul>
        <li>选择模型（右键点击）</li>
        <li>按 <code>S</code> 键进入缩放模式</li>
        <li>输入数字（如 0.1 缩小，10 放大）</li>
        <li>按回车确认</li>
      </ul>
    </div>

    <h2>📞 获取帮助</h2>
    <ul>
      <li>🌐 官方文档: <a href="https://docs.meshy.ai" target="_blank">https://docs.meshy.ai</a></li>
      <li>💬 GitHub Issues: <a href="https://github.com/Meshy-ai/meshy-blender-plugin/issues" target="_blank">插件问题反馈</a></li>
      <li>🎓 Blender官方教程: <a href="https://www.blender.org/support/tutorials/" target="_blank">https://www.blender.org/support/tutorials/</a></li>
    </ul>

    <hr style="margin: 30px 0; border: none; border-top: 2px solid #ecf0f1;">
    
    <p style="text-align: center; color: #7f8c8d; font-size: 14px;">
      最后更新: 2025年10月22日 | 适用版本: v0.5.5+
    </p>
  </div>
</body>
</html>
                          `
                          const newWindow = window.open('', '_blank')
                          newWindow.document.write(guideContent)
                          newWindow.document.close()
                          toast.success('📖 使用指南已打开')
                        }}
                        className="w-full flex items-center justify-between px-3 py-2 text-sm text-gray-300 hover:text-white hover:bg-white/10 rounded-lg transition-all"
                      >
                        <span className="flex items-center space-x-2">
                          <span>📖</span>
                          <span>使用指南</span>
                        </span>
                        <span className="text-xs text-gray-500">查看</span>
                      </button>

                      {/* 关闭菜单按钮 */}
                      <div className="border-t border-white/10 my-1"></div>
                      <button
                        onClick={() => setShowDownloadMenu(false)}
                        className="w-full flex items-center justify-center px-3 py-2 text-sm text-gray-400 hover:text-white hover:bg-red-500/20 rounded-lg transition-all group"
                      >
                        <span className="flex items-center space-x-2">
                          <span className="group-hover:scale-110 transition-transform">✕</span>
                          <span>关闭菜单</span>
                        </span>
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      {/* 控制面板 */}
      {modelUrl && showControls && (
        <div className="mb-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4 bg-white/5 rounded-xl border border-white/10 animate-scale-in">
          {/* 自动旋转 */}
          <div>
            <label className="flex items-center justify-between text-sm text-gray-300 mb-2">
              <span className="flex items-center space-x-2">
                <svg className="w-4 h-4 text-accent-purple" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                <span>自动旋转</span>
              </span>
              <button
                onClick={() => setAutoRotate(!autoRotate)}
                className={`relative w-12 h-6 rounded-full transition-colors ${
                  autoRotate ? 'bg-accent-purple' : 'bg-white/20'
                }`}
              >
                <div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
                  autoRotate ? 'translate-x-7' : 'translate-x-1'
                }`} />
              </button>
            </label>
          </div>

          {/* 显示网格 */}
          <div>
            <label className="flex items-center justify-between text-sm text-gray-300 mb-2">
              <span className="flex items-center space-x-2">
                <svg className="w-4 h-4 text-accent-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h4a1 1 0 011 1v7a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM14 5a1 1 0 011-1h4a1 1 0 011 1v7a1 1 0 01-1 1h-4a1 1 0 01-1-1V5zM4 16a1 1 0 011-1h4a1 1 0 011 1v3a1 1 0 01-1 1H5a1 1 0 01-1-1v-3zM14 16a1 1 0 011-1h4a1 1 0 011 1v3a1 1 0 01-1 1h-4a1 1 0 01-1-1v-3z" />
                </svg>
                <span>显示网格</span>
              </span>
              <button
                onClick={() => setShowGrid(!showGrid)}
                className={`relative w-12 h-6 rounded-full transition-colors ${
                  showGrid ? 'bg-accent-blue' : 'bg-white/20'
                }`}
              >
                <div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
                  showGrid ? 'translate-x-7' : 'translate-x-1'
                }`} />
              </button>
            </label>
          </div>

          {/* 光照强度 */}
          <div>
            <label className="text-sm text-gray-300 mb-2 flex items-center space-x-2">
              <svg className="w-4 h-4 text-accent-yellow" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
              </svg>
              <span>光照强度: {lightIntensity.toFixed(1)}</span>
            </label>
            <input
              type="range"
              min="0"
              max="3"
              step="0.1"
              value={lightIntensity}
              onChange={(e) => setLightIntensity(parseFloat(e.target.value))}
              className="w-full h-2 bg-white/10 rounded-lg appearance-none cursor-pointer accent-accent-purple"
            />
          </div>

          {/* 环境光强度 */}
          <div>
            <label className="text-sm text-gray-300 mb-2 flex items-center space-x-2">
              <svg className="w-4 h-4 text-accent-cyan" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
              </svg>
              <span>环境光: {ambientIntensity.toFixed(1)}</span>
            </label>
            <input
              type="range"
              min="0"
              max="2"
              step="0.1"
              value={ambientIntensity}
              onChange={(e) => setAmbientIntensity(parseFloat(e.target.value))}
              className="w-full h-2 bg-white/10 rounded-lg appearance-none cursor-pointer accent-accent-cyan"
            />
          </div>

          {/* 材质类型 */}
          <div className="md:col-span-2">
            <label className="text-sm text-gray-300 mb-2 flex items-center space-x-2">
              <svg className="w-4 h-4 text-accent-pink" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
              </svg>
              <span>显示模式</span>
            </label>
            <div className="flex space-x-2">
              {[
                { value: 'standard', label: '标准', icon: '🎨' },
                { value: 'wireframe', label: '线框', icon: '🔲' },
                { value: 'normal', label: '法线', icon: '🌈' }
              ].map((mode) => (
                <button
                  key={mode.value}
                  onClick={() => setMaterialType(mode.value)}
                  className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                    materialType === mode.value
                      ? 'bg-accent-purple text-white'
                      : 'bg-white/5 text-gray-300 hover:bg-white/10'
                  }`}
                >
                  <span className="mr-1">{mode.icon}</span>
                  {mode.label}
                </button>
              ))}
            </div>
          </div>

          {/* 模型缩放 */}
          <div>
            <label className="text-sm text-gray-300 mb-2 flex items-center space-x-2">
              <svg className="w-4 h-4 text-accent-green" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7" />
              </svg>
              <span>模型缩放: {modelScale.toFixed(1)}x</span>
            </label>
            <input
              type="range"
              min="0.1"
              max="3"
              step="0.1"
              value={modelScale}
              onChange={(e) => setModelScale(parseFloat(e.target.value))}
              className="w-full h-2 bg-white/10 rounded-lg appearance-none cursor-pointer accent-accent-green"
            />
          </div>

          {/* 旋转速度 */}
          {autoRotate && (
            <div>
              <label className="text-sm text-gray-300 mb-2 flex items-center space-x-2">
                <svg className="w-4 h-4 text-accent-orange" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span>旋转速度: {rotationSpeed.toFixed(1)}</span>
              </label>
              <input
                type="range"
                min="0.1"
                max="2"
                step="0.1"
                value={rotationSpeed}
                onChange={(e) => setRotationSpeed(parseFloat(e.target.value))}
                className="w-full h-2 bg-white/10 rounded-lg appearance-none cursor-pointer accent-accent-orange"
              />
            </div>
          )}

          {/* 背景颜色 */}
          <div>
            <label className="text-sm text-gray-300 mb-2 flex items-center space-x-2">
              <svg className="w-4 h-4 text-accent-pink" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
              </svg>
              <span>背景颜色</span>
            </label>
            <div className="flex space-x-2">
              {[
                { value: '#1a1a2e', label: '深色', color: 'bg-gray-900' },
                { value: '#ffffff', label: '白色', color: 'bg-white' },
                { value: '#0f3460', label: '蓝色', color: 'bg-blue-900' },
                { value: '#16213e', label: '深蓝', color: 'bg-blue-950' }
              ].map((bg) => (
                <button
                  key={bg.value}
                  onClick={() => setBackgroundColor(bg.value)}
                  className={`flex-1 px-2 py-1 rounded text-xs transition-all ${
                    backgroundColor === bg.value
                      ? 'ring-2 ring-accent-purple'
                      : 'opacity-70 hover:opacity-100'
                  }`}
                  title={bg.label}
                >
                  <div className={`w-full h-6 rounded ${bg.color} border border-white/20`}></div>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* 预设视角快捷按钮 */}
      {modelUrl && (
        <div className="mb-4 flex flex-wrap gap-2">
          <button
            onClick={resetCamera}
            className="px-3 py-1.5 bg-white/5 hover:bg-white/10 text-gray-300 hover:text-white rounded-lg transition-all text-xs border border-white/10 hover:border-accent-purple/50"
          >
            🔄 重置
          </button>
          {Object.entries(CAMERA_PRESETS).map(([key, preset]) => (
            <button
              key={key}
              onClick={() => applyPreset(preset)}
              className="px-3 py-1.5 bg-white/5 hover:bg-accent-purple/20 text-gray-300 hover:text-white rounded-lg transition-all text-xs border border-white/10 hover:border-accent-purple/50"
            >
              {preset.name}
            </button>
          ))}
        </div>
      )}

      {/* 3D画布区域 */}
      <div 
        ref={canvasRef}
        className={`relative rounded-xl overflow-hidden border border-white/5 ${
          isFullscreen ? 'h-[calc(100vh-200px)]' : 'h-64 md:h-96 lg:h-[500px]'
        }`}
        style={{ backgroundColor }}
      >
        {!modelUrl && !isGenerating && (
          <div className="absolute inset-0 flex flex-col items-center justify-center text-gray-400 p-6">
            <div className="text-8xl mb-6 animate-float">🎯</div>
            <p className="text-xl font-semibold text-gray-300 mb-3">开始您的 3D 创作之旅</p>
            <p className="text-sm text-gray-500 mb-8 text-center max-w-md">
              上传产品图片，AI 将自动生成高质量 3D 模型，支持 360° 旋转查看和多种材质预览
            </p>
            
            {/* 快速开始步骤 */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 w-full max-w-2xl">
              <div className="p-4 bg-white/5 rounded-lg border border-white/10 hover:border-accent-purple/50 transition-all">
                <div className="text-3xl mb-2 text-center">📸</div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-white mb-1">步骤 1</div>
                  <div className="text-xs text-gray-400">上传产品图片</div>
                </div>
              </div>
              
              <div className="p-4 bg-white/5 rounded-lg border border-white/10 hover:border-accent-blue/50 transition-all">
                <div className="text-3xl mb-2 text-center">🤖</div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-white mb-1">步骤 2</div>
                  <div className="text-xs text-gray-400">AI 生成 3D 模型</div>
                </div>
              </div>
              
              <div className="p-4 bg-white/5 rounded-lg border border-white/10 hover:border-accent-cyan/50 transition-all">
                <div className="text-3xl mb-2 text-center">🎨</div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-white mb-1">步骤 3</div>
                  <div className="text-xs text-gray-400">预览并定制</div>
                </div>
              </div>
            </div>
            
            {/* 功能特点 */}
            <div className="mt-8 flex flex-wrap justify-center gap-3 text-xs">
              <div className="flex items-center space-x-1 px-3 py-1 bg-white/5 rounded-full border border-white/10">
                <span className="text-accent-purple">✓</span>
                <span className="text-gray-300">360° 旋转查看</span>
              </div>
              <div className="flex items-center space-x-1 px-3 py-1 bg-white/5 rounded-full border border-white/10">
                <span className="text-accent-blue">✓</span>
                <span className="text-gray-300">多材质预览</span>
              </div>
              <div className="flex items-center space-x-1 px-3 py-1 bg-white/5 rounded-full border border-white/10">
                <span className="text-accent-cyan">✓</span>
                <span className="text-gray-300">实时尺寸调整</span>
              </div>
              <div className="flex items-center space-x-1 px-3 py-1 bg-white/5 rounded-full border border-white/10">
                <span className="text-accent-pink">✓</span>
                <span className="text-gray-300">一键截图保存</span>
              </div>
            </div>
          </div>
        )}

        {isGenerating && (
          <div className="absolute inset-0 flex flex-col items-center justify-center glass-effect-dark z-10">
            <div className="relative">
              <div className="text-6xl mb-4 animate-bounce">⚙️</div>
              <div className="absolute inset-0 bg-accent-purple/30 rounded-full blur-2xl animate-pulse"></div>
            </div>
            <p className="text-xl font-semibold text-white mb-2">AI 正在生成 3D 模型...</p>
            <p className="text-sm text-gray-400">这可能需要 1-2 分钟，请耐心等待</p>
            <div className="mt-6 flex space-x-2">
              <div className="w-3 h-3 bg-accent-purple rounded-full animate-bounce" style={{ animationDelay: '0s' }}></div>
              <div className="w-3 h-3 bg-accent-blue rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
              <div className="w-3 h-3 bg-accent-cyan rounded-full animate-bounce" style={{ animationDelay: '0.4s' }}></div>
            </div>
          </div>
        )}

        {modelUrl && (
          <Canvas shadows dpr={[1, 2]} camera={{ position: [0, 0, 10], fov: 50 }}>
            <Suspense fallback={<LoadingPlaceholder />}>
              {/* 照明 */}
              <ambientLight intensity={ambientIntensity} />
              <directionalLight
                position={[10, 10, 5]}
                intensity={lightIntensity}
                castShadow
                shadow-mapSize-width={1024}
                shadow-mapSize-height={1024}
              />
              <pointLight position={[-10, -10, -5]} intensity={lightIntensity * 0.5} />
              <spotLight position={[0, 10, 0]} intensity={lightIntensity * 0.3} />
              
              {/* 模型 */}
              <Model 
                url={modelUrl} 
                autoRotate={autoRotate} 
                materialType={materialType}
                modelScale={modelScale}
                rotationSpeed={rotationSpeed}
                onModelLoad={setModelInfo}
              />
              
              {/* 网格辅助线 */}
              {showGrid && (
                <>
                  <gridHelper args={[10, 10, '#667eea', '#764ba2']} />
                  <axesHelper args={[5]} />
                </>
              )}
              
              {/* 轨道控制器 - 移动端优化 */}
              <OrbitControls
                ref={controlsRef}
                enablePan={true}
                enableZoom={true}
                enableRotate={true}
                minDistance={1}
                maxDistance={50}
                autoRotate={false}
                autoRotateSpeed={0.5}
                // 移动端触摸优化
                touches={{
                  ONE: THREE.TOUCH.ROTATE,
                  TWO: THREE.TOUCH.DOLLY_PAN
                }}
                enableDamping={true}
                dampingFactor={0.05}
                rotateSpeed={isMobile ? 0.8 : 1}
                zoomSpeed={isMobile ? 0.8 : 1}
                panSpeed={isMobile ? 0.8 : 1}
                minPolarAngle={0}
                maxPolarAngle={Math.PI}
              />
            </Suspense>
          </Canvas>
        )}
      </div>

      {/* 模型信息面板 */}
      {modelUrl && modelInfo && showModelInfo && !isFullscreen && (
        <div className="mt-4 p-4 bg-gradient-to-br from-white/5 to-white/10 rounded-xl border border-white/10 animate-scale-in">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold text-white flex items-center space-x-2">
              <svg className="w-4 h-4 text-accent-cyan" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
              <span>模型统计信息</span>
            </h3>
            <button
              onClick={() => setShowModelInfo(false)}
              className="text-gray-400 hover:text-white transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {/* 顶点数 */}
            <div className="p-3 bg-white/5 rounded-lg border border-white/10">
              <div className="text-xs text-gray-400 mb-1">顶点数</div>
              <div className="text-lg font-bold text-white flex items-baseline">
                {modelInfo.vertices?.toLocaleString()}
                <span className="text-xs text-accent-purple ml-1 font-normal">个</span>
              </div>
            </div>
            
            {/* 面数 */}
            <div className="p-3 bg-white/5 rounded-lg border border-white/10">
              <div className="text-xs text-gray-400 mb-1">三角面</div>
              <div className="text-lg font-bold text-white flex items-baseline">
                {modelInfo.faces?.toLocaleString()}
                <span className="text-xs text-accent-blue ml-1 font-normal">个</span>
              </div>
            </div>
            
            {/* 质量评级 */}
            <div className="p-3 bg-white/5 rounded-lg border border-white/10">
              <div className="text-xs text-gray-400 mb-1">模型质量</div>
              <div className="text-lg font-bold text-green-400 flex items-center space-x-1">
                {modelInfo.faces < 10000 ? (
                  <>
                    <span>简洁</span>
                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                    </svg>
                  </>
                ) : modelInfo.faces < 50000 ? (
                  <>
                    <span>标准</span>
                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                    </svg>
                  </>
                ) : (
                  <>
                    <span>精细</span>
                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                    </svg>
                  </>
                )}
              </div>
            </div>
            
            {/* 打印难度 */}
            <div className="p-3 bg-white/5 rounded-lg border border-white/10">
              <div className="text-xs text-gray-400 mb-1">打印难度</div>
              <div className="text-lg font-bold text-accent-cyan">
                {modelInfo.faces < 10000 ? '简单' : modelInfo.faces < 50000 ? '中等' : '复杂'}
              </div>
            </div>
          </div>
          
          {/* 模型尺寸 */}
          {modelInfo.size && (
            <div className="mt-3 p-3 bg-white/5 rounded-lg border border-white/10">
              <div className="text-xs text-gray-400 mb-2">模型尺寸（原始单位）</div>
              <div className="flex items-center justify-around text-sm">
                <div className="text-center">
                  <div className="text-gray-400 text-xs mb-1">长 (X)</div>
                  <div className="text-white font-semibold">{modelInfo.size.x}</div>
                </div>
                <div className="text-gray-600">×</div>
                <div className="text-center">
                  <div className="text-gray-400 text-xs mb-1">高 (Y)</div>
                  <div className="text-white font-semibold">{modelInfo.size.y}</div>
                </div>
                <div className="text-gray-600">×</div>
                <div className="text-center">
                  <div className="text-gray-400 text-xs mb-1">宽 (Z)</div>
                  <div className="text-white font-semibold">{modelInfo.size.z}</div>
                </div>
              </div>
            </div>
          )}
          
          {/* 打印预估时间 */}
          <div className="mt-3 flex items-center justify-between p-3 bg-gradient-to-r from-accent-purple/10 to-accent-blue/10 rounded-lg border border-accent-purple/30">
            <div className="flex items-center space-x-2">
              <svg className="w-5 h-5 text-accent-purple" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span className="text-sm text-gray-300">预估打印时间</span>
            </div>
            <div className="text-white font-bold">
              {Math.ceil(modelInfo.faces / 2000)} - {Math.ceil(modelInfo.faces / 1000)} 小时
            </div>
          </div>
        </div>
      )}
      
      {/* 重新显示模型信息按钮 */}
      {modelUrl && !showModelInfo && !isFullscreen && (
        <div className="mt-4 animate-scale-in">
          <button
            onClick={() => setShowModelInfo(true)}
            className="w-full p-2 bg-white/5 hover:bg-white/10 text-gray-300 hover:text-white rounded-lg border border-white/10 hover:border-accent-cyan/50 transition-all duration-300 flex items-center justify-center space-x-2"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span className="text-sm">显示模型统计信息</span>
          </button>
        </div>
      )}

      {/* 操作说明 - 根据设备类型显示不同提示 */}
      {modelUrl && !isFullscreen && (
        <div className="mt-6 grid grid-cols-3 gap-2 md:gap-3 text-sm">
          <div className="p-3 md:p-4 bg-white/5 rounded-xl text-center border border-white/10 hover:border-accent-purple/50 transition-all duration-300 group">
            <div className="font-semibold text-white mb-1 md:mb-2 flex items-center justify-center space-x-1">
              <svg className="w-4 h-4 md:w-5 md:h-5 text-accent-purple" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 11.5V14m0-2.5v-6a1.5 1.5 0 113 0m-3 6a1.5 1.5 0 00-3 0v2a7.5 7.5 0 0015 0v-5a1.5 1.5 0 00-3 0m-6-3V11m0-5.5v-1a1.5 1.5 0 013 0v1m0 0V11m0-5.5a1.5 1.5 0 013 0v3m0 0V11" />
              </svg>
              <span className="text-xs md:text-sm">旋转</span>
            </div>
            <div className="text-gray-400 text-xs">
              {isTouchDevice ? '单指拖动' : '左键拖动'}
            </div>
          </div>
          <div className="p-3 md:p-4 bg-white/5 rounded-xl text-center border border-white/10 hover:border-accent-blue/50 transition-all duration-300 group">
            <div className="font-semibold text-white mb-1 md:mb-2 flex items-center justify-center space-x-1">
              <svg className="w-4 h-4 md:w-5 md:h-5 text-accent-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7" />
              </svg>
              <span className="text-xs md:text-sm">缩放</span>
            </div>
            <div className="text-gray-400 text-xs">
              {isTouchDevice ? '双指捏合' : '滚轮'}
            </div>
          </div>
          <div className="p-3 md:p-4 bg-white/5 rounded-xl text-center border border-white/10 hover:border-accent-cyan/50 transition-all duration-300 group">
            <div className="font-semibold text-white mb-1 md:mb-2 flex items-center justify-center space-x-1">
              <svg className="w-4 h-4 md:w-5 md:h-5 text-accent-cyan" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
              </svg>
              <span className="text-xs md:text-sm">平移</span>
            </div>
            <div className="text-gray-400 text-xs">
              {isTouchDevice ? '双指拖动' : '右键拖动'}
            </div>
          </div>
        </div>
      )}

      {/* 模型信息 */}
      {modelUrl && useStore.getState().modelData && !isFullscreen && (
        <div className="mt-6 p-4 bg-gradient-to-r from-green-500/10 to-emerald-500/10 rounded-xl border border-green-500/30 backdrop-blur-sm">
          <p className="text-sm text-gray-300 flex items-center space-x-2">
            <svg className="w-5 h-5 text-green-400 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
            </svg>
            <span>
              <strong className="text-green-400">模型生成成功！</strong>
              <span className="text-gray-400 ml-2">您可以 360° 旋转查看效果，按 F 进入全屏</span>
            </span>
          </p>
        </div>
      )}
    </div>
  )
}

// 预加载模型（性能优化）
export function preloadModel(url) {
  // 不预加载内置演示模型
  if (url && url !== '__builtin_demo__') {
    // 将MeshyAI的CDN URL转换为代理URL
    const getProxyUrl = (originalUrl) => {
      if (!originalUrl) return originalUrl
      if (originalUrl.includes('assets.meshy.ai')) {
        return originalUrl.replace('https://assets.meshy.ai', '/meshy-assets')
      }
      return originalUrl
    }
    
    const proxyUrl = getProxyUrl(url)
    useGLTF.preload(proxyUrl)
  }
}

